//
//  TingshuoTestCollectionViewCell.m
//  Learn
//
//  Created by  on 2024/4/13.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "TingshuoTestCollectionViewCell.h"
#import "QuestionOptionTableViewCell.h"
#import "PlayManager.h"

@interface TingshuoTestCollectionViewCell ()<PlayManagerDelegate>
@property (nonatomic, assign) BOOL isReadingStem;//是否在读题干

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSInteger lastTime;

@property (nonatomic, assign) NSInteger allTime;

@property (nonatomic, assign) BOOL recordStartWarn;//是否播放开始录音提示语

@property (nonatomic, assign) BOOL recordEndWarn;//是否播放开始录音提示语
@end

@implementation TingshuoTestCollectionViewCell

- (void)awakeFromNib {
    [super awakeFromNib];

    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 180;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.scrollEnabled = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"QuestionOptionTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"QuestionOptionTableViewCell"];
    // Initialization code
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1 + 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QuestionOptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QuestionOptionTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"QuestionOptionTableViewCell" owner:self options:nil] lastObject];
    }
    cell.resmain = self.resmain;
    cell.imgH.constant = 0;
    cell.imgV.hidden = YES;
    cell.textLB.text = @"";
    if (indexPath.row == 0) {
        cell.textLB.text = self.model.templateSettings.content;
    } else {
        
        cell.textLB.text = self.showQuestion.trunk.body;
        if (self.step == answer_step_title_read) {
            
            if (self.model.templateSettings.listeningAndSpeakingRule.lookTime > 0||self.model.templateSettings.listeningAndSpeakingRule.rootLookTime > 0) {
                
                cell.textLB.text = @"";
                
            }
        }
        
        if (self.step != answer_step_title_read) {
            
            NSString *imgStr = @"";
           
            for (HSValueAttachment *att in self.showQuestion.trunk.attachments) {
                if (att.fileType == 1) {
                    imgStr =[NSString stringWithFormat:@"%@%@",self.resmain,att.url];
                }
            }
            if (imgStr.length != 0) {
                cell.imgV.hidden = NO;
                [cell.imgV sd_setImageWithURL:[NSURL URLWithString:imgStr] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    
                    cell.imgH.constant = image.size.height/image.size.width*(SCREEN_W - 40);
                }];
            }
        
        }
    
    }
    cell.textLB.textColor = ![cell.textLB.text isEqualToString:self.playingText]?rgba(181, 181, 181, 1):rgba(51, 51, 51, 1);
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //    if (indexPath.row > 0) {
    //        HSQuestion *testModel = self.model.questions[indexPath.row - 1];
    //        if (testModel.trunk.attachments.count != 0) {
    //            NSString *imurl = [NSString stringWithFormat:@"%@%@",self.resmain,testModel.trunk.attachments.firstObject.url];
    //            [[PlayManager sharPlayManager] playerWithURL:imurl];
    //        }
    //    } else {
    //        NSString *imurl = [NSString stringWithFormat:@"%@%@",self.resmain,self.model.templateSettings.audioUrl];
    //        [[PlayManager sharPlayManager] playerWithURL:imurl];
    //    }
    
}

- (void)hidenViews
{
    
    self.bottomView.hidden = YES;
    self.nextBtn.hidden = YES;
    self.statuesImg.hidden = YES;
    self.progressView.hidden = YES;
    
}
- (void)setModel:(HSItem *)model {
    
    _model = model;
    
}
- (void)startTest
{
    PlayManager.sharPlayManager.delegate = self;
    [self stop];
    self.step = answer_step_title_read;
    self.questionIsDoingIndex = 0;//正在第几题
    self.isDoingSubQuestionIndex = 0;//正在第几题
    self.currentReadTime = 0;//正在读第几遍
    self.questions = nil;
    self.recordStartWarn = NO;
    self.recordEndWarn = NO;
    self.showQuestion = nil;
    
    self.lastTime = 0;
    self.bottomView.hidden = YES;
    self.playingText = self.model.templateSettings.content;
   
    self.progressView.hidden = ![PlayManager sharPlayManager].isBeginTest;
    self.statuesImg.hidden = ![PlayManager sharPlayManager].isBeginTest;
    self.nextBtn.hidden = ![PlayManager sharPlayManager].isBeginTest;
    [self.statuesImg setImage:[self getGifImageWithName:@"speaker"]];
    self.questions = self.model.questions;
    int index = self.questionIsDoingIndex;
    self.showQuestion = self.questions[index];
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[PlayManager sharPlayManager] pause];
        if (![PlayManager sharPlayManager].isBeginTest) {
           
            self.progressView.hidden = YES;
            NSString *path = [[NSBundle mainBundle] pathForResource:@"beginTest" ofType:@"mp3"];
            NSString *imurl = [NSString stringWithFormat:@"file://%@",path];
            [[PlayManager sharPlayManager] playerWithURL:imurl];
            
        }else{
            
            self.progressView.hidden = NO;
            [[PlayManager sharPlayManager] pause];
            NSString *imurl = [NSString stringWithFormat:@"%@%@",self.resmain,self.model.templateSettings.audioUrl];
            [[PlayManager sharPlayManager] playerWithURL:imurl];
            
        }
        
    });
}
-(void)clickToNext
{
    if (self.step == answer_step_look_question) {
        
        self.step = answer_step_read_content;
        [self playContent];
        
        
    }else if (self.step == answer_step_wait_read) {
        
        if (self.showQuestion.children.count > 0) {
            self.currentReadTime = 0;
            self.step = answer_step_read_sub_question;
            [self playQuestion];
            return;
        }else{
            if (self.recordStartWarn) {
                self.recordStartWarn = NO;
                [self recordContent];
            }else{
                [self playRecordWarnStart];
            }
           
        }
       
    }else  if (self.step == answer_step_sub_wait_read) {
        
        [self playRecordWarnStart];
       
    }else if (self.step == answer_step_answe_sub_questionr_record) {
        
        [self.detection stop];
        [self playRecordWarnEnd];
        
    }else if (self.step == answer_step_answer_record) {
        
        [self.detection stop];
        [self playRecordWarnEnd];
        
    }else{
        [self musicFinsh];
    }
}
- (void)timerFired:(NSTimer *)timer {
    // 计时器触发时执行的方法
    [self setTimeStr];
    
    if (self.lastTime <= 0) {
        [self.timer invalidate];
        self.timer = nil;
        [self hidenViews];
        self.progressView.progress = 0;
        if (self.step == answer_step_look_question) {
            self.step = answer_step_read_content;
            [self playContent];
            return;
            
        }
        if (self.step == answer_step_wait_read) {
            
            if (self.showQuestion.children.count > 0) {
                self.currentReadTime = 0;
                self.step = answer_step_read_sub_question;
                [self playQuestion];
                return;
            }else{
                if (self.recordStartWarn) {
                    self.recordStartWarn = NO;
                    [self recordContent];
                }else{
                    [self playRecordWarnStart];
                }
               
            }
            return;
        }
        if (self.step == answer_step_sub_wait_read) {
            
            [self playRecordWarnStart];
            return;
        }
        if (self.step == answer_step_answe_sub_questionr_record) {
            [self.detection stop];
            [self playRecordWarnEnd];
        }
        
        if (self.step == answer_step_answer_record) {
            
            [self.detection stop];
            [self playRecordWarnEnd];
            
        }
        
    }else{
        self.progressView.progress = (self.allTime - self.lastTime)*1.0/self.allTime*1.0;
    }
    self.lastTime --;
    
}
- (void)nextQuestion
{
    self.questionIsDoingIndex =  self.questionIsDoingIndex + 1;
    self.currentReadTime = 0;
    if (self.questionIsDoingIndex > 1) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathWithIndex:self.questionIsDoingIndex] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
    }    
    [self playContent];
}
- (void)nextSubQuestion
{
    self.currentReadTime = 0;
    [self.detection stop];
    self.isDoingSubQuestionIndex =  self.isDoingSubQuestionIndex + 1;
    self.step = answer_step_read_sub_question;
    [self playQuestion];
}
- (void)recordContent
{
    [self stop];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    self.step = answer_step_answer_record;
    [self.statuesImg setImage:[self getGifImageWithName:@"record"]];
    self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.answerTime;
    [self recordTextWithQuestion:self.showQuestion];
    [self initTimer];
    });
}
- (void)recordSubQuestionAnswer
{
    
    [self stop];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.step = answer_step_answe_sub_questionr_record;
        [self.statuesImg setImage:[self getGifImageWithName:@"record"]];
        self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.answerTime;
        [self recordTextWithQuestion:self.showQuestion];
        [self initTimer];
    });
    
}

- (void)recordTextWithQuestion:(HSQuestion *)question{
    
    //开始录音
    void(^StartSpeakingVoice)(void) = ^() {
        
        self.detection.question = self.showQuestion;
        NSString *str = self.showQuestion.answer;
        if (self.showQuestion.type == 6) {
            str = [str componentsSeparatedByString:@"\n"].firstObject;
        }
        str = [str stringByReplacingOccurrencesOfString:@"(" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@")" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"（" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"）" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"[" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"[" withString:@""];
//        if (str.length > 100) {
//            str = [str substringToIndex:99];
//        }
//        if (self.showQuestion.type == 6) {
//            NSString *str = self.showQuestion.trunk.body;
//            NSString *quest = [str componentsSeparatedByString:@"\n"].firstObject;
//            NSString *choice = [str componentsSeparatedByString:@"\n"].lastObject;
//            choice = [choice stringByReplacingOccurrencesOfString:@"(" withString:@""];
//            choice = [choice stringByReplacingOccurrencesOfString:@")" withString:@""];
//            NSArray *wrd = [choice componentsSeparatedByString:@"/"];
//            choice = @"";
//            for (int i = 0; i < wrd.count; i++) {
//                choice = [NSString stringWithFormat:@"%@%d.%@\n",choice,i+1,wrd[i]];
//            }
//            choice =[NSString stringWithFormat:@"%@[keywords]\n%@[question]%@",choice,self.detection.question.answer,quest];
//            [self.detection startEvalutingWord:choice];
//        }else{
//            [self.detection startEvalutingWord:self.detection.question.answer];
//        }
        [self.detection startEvalutingWord:str];
       //[NSString stringWithFormat:@"%@",@""]
        
    };
    
    //检测是否授权麦克风
    void(^CheckOutAuthorization)(void) = ^() {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            //第一次询问用户是否进行授权
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                if (granted) {
                    StartSpeakingVoice();
                }
            }];
        }
        else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {// 未授权
            //            NSString *message = @"\n麦克风权限未开启，请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能";
            //            [[UIViewController ge] alertViewTitle:@"麦克风权限未开启" message:message left:@"确定" leftBlock:^{
            //
            //            } right:@"前往" rightBlock:^{
            //                //跳入当前App设置界面
            //                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            //            }];
        }
        else{// 已授权
            StartSpeakingVoice();
        }
    };
    
    CheckOutAuthorization();
    
}

- (void)playContent
{
    [self stop];
    [self.statuesImg setImage:[self getGifImageWithName:@"speaker"] ];
    
    if (self.model.questions.count == 0) {
        return;
    }
    int index = self.questionIsDoingIndex;
    HSQuestion *tr = self.model.questions[index];
    self.showQuestion = tr;
    HSValueAttachment *k= tr.trunk.attachments[0];
    for (HSValueAttachment *att in self.showQuestion.trunk.attachments) {
        if (att.fileType == 2) {
            k = att;
        }
    }
    self.playingText = tr.trunk.body;
    NSString *imurl = [NSString stringWithFormat:@"%@%@",self.resmain,k.url];
    [[PlayManager sharPlayManager] playerWithURL:imurl];
    [self.tableView reloadData];
}

- (void)playQuestion
{
    [self stop];
    [self.statuesImg setImage:[self getGifImageWithName:@"speaker"] ];
   
    if (self.model.questions.count == 0) {
        return;
    }
    int index = self.questionIsDoingIndex;
    int indexSub = self.isDoingSubQuestionIndex;
    HSQuestion *tr = self.model.questions[index];
    self.showQuestion = tr.children[indexSub];
    HSValueAttachment *k= self.showQuestion.trunk.attachments[0];
    for (HSValueAttachment *att in self.showQuestion.trunk.attachments) {
        if (att.fileType == 2) {
            k = att;
        }
    }
    self.playingText = self.showQuestion.trunk.body;
    NSString *imurl = [NSString stringWithFormat:@"%@%@",self.resmain,k.url];
    [[PlayManager sharPlayManager] playerWithURL:imurl];
    [self.tableView reloadData];
    
}

- (void)playRecordWarnStart
{
    [self stop];
    self.recordStartWarn = YES;
    [self hidenViews];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"begin_record" ofType:@"mp3"];
    NSString *imurl = [NSString stringWithFormat:@"file://%@",path];
    [[PlayManager sharPlayManager] playerWithURL:imurl];
   
}
- (void)playRecordWarnEnd
{
    [self stop];
    self.recordEndWarn = YES;
    [self hidenViews];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"stop_record" ofType:@"mp3"];
    NSString *imurl = [NSString stringWithFormat:@"file://%@",path];
    [[PlayManager sharPlayManager] playerWithURL:imurl];
    
}
- (void)initTimer
{
    self.progressView.progress = 0;
    [self setTimeStr];
    [self.timer invalidate];
    self.timer = nil;
    self.allTime = self.lastTime;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(timerFired:)
                                                userInfo:nil
                                                 repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
}
- (void)setTimeStr
{
    self.bottomView.hidden = NO;
    self.statuesImg.hidden = NO;
    self.nextBtn.hidden = NO;
    self.progressView.hidden = NO;
    NSString *title = [NSString stringWithFormat:@"正在播放原音 剩余%02lds", self.lastTime];
    if (self.step == answer_step_look_question) {
        title = [NSString stringWithFormat:@"阅读时间 剩余%02lds", self.lastTime];
    }else if (self.step == answer_step_read_content)
    {
        NSString *str = self.currentReadTime > 0?@"再一遍播放原音":@"正在播放原音";
        title = [NSString stringWithFormat:@"%@ 剩余%02lds",str, self.lastTime];
    }else if (self.step == answer_step_read_sub_question)
    {
        NSString *str = self.currentReadTime > 0?@"再一遍播放原音":@"正在播放原音";
        title = [NSString stringWithFormat:@"%@ 剩余%02lds",str, self.lastTime];
    }else if (self.step == answer_step_wait_read||self.step == answer_step_sub_wait_read)
    {
        title = [NSString stringWithFormat:@"准备时间 剩余%02lds", self.lastTime];
    }else if (self.step == answer_step_answer_record)
    {
        title = [NSString stringWithFormat:@"录音时间 剩余%02lds", self.lastTime];
    }else if (self.step == answer_step_answe_sub_questionr_record)
    {
        title = [NSString stringWithFormat:@"录音时间 剩余%02lds", self.lastTime];
    }
    
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:title];
    [att addAttribute:NSForegroundColorAttributeName value:rgba(12, 183, 108, 1) range:NSMakeRange(title.length - 3, 3)];
    self.timeL.attributedText = att;
}

- (void)playerWithPlayer:(AVPlayer *)player
                progress:(float)progress
                duration:(float)duration currentTime:(float)currentTime
{
    if ([PlayManager sharPlayManager].isBeginTest) {
        if (self.recordEndWarn||self.recordStartWarn) {
            return;
        }
        if (!self.model.isRead) {
            self.model.isRead = YES;
        }
        if (self.step == answer_step_read_content||self.step == answer_step_read_sub_question||self.step == answer_step_title_read) {
            self.progressView.progress =  progress;
            self.lastTime = duration - currentTime;
            [self setTimeStr];
        }
      
    }
    
}
- (void)playStateChange:(AVPlayerItemStatus)state
{
    if (state != AVPlayerItemStatusReadyToPlay) {
        [self clickToNext];
    }
}
- (void)stop
{
    [self.timer invalidate];
    self.timer = nil;
    [self.detection stop];
    [[PlayManager sharPlayManager] pause];
}
- (void)stopActivity
{
    self.progressView.progress = 0;
    [self stop];
    self.readFinishBlock(self.model);
   
}
- (void)musicFinsh
{
    
    [self stop];
    if (![PlayManager sharPlayManager].isBeginTest) {
        [PlayManager sharPlayManager].isBeginTest = YES;
        [self startTest];
        return;
    }
    
    if (self.showQuestion.type == 5) {
        self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.rootReadyTime;
    }else{
        self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.readyTime;
    }
    NSInteger views = 0;
    if (self.showQuestion.type == 5) {
        views = self.model.templateSettings.listeningAndSpeakingRule.rootAudioViews;
    }else{
        views = self.model.templateSettings.listeningAndSpeakingRule.audioViews;
    }
    
    
    if (self.step == answer_step_title_read) {
        
        if (self.model.templateSettings.listeningAndSpeakingRule.lookTime > 0||self.model.templateSettings.listeningAndSpeakingRule.rootLookTime > 0) {
            self.step = answer_step_look_question;
            if (self.model.templateSettings.listeningAndSpeakingRule.lookTime > 0)
            {
                self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.lookTime;
            }
            if (self.model.templateSettings.listeningAndSpeakingRule.rootLookTime > 0)
            {
                self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.rootLookTime;
            }
           
            self.playingText = self.showQuestion.trunk.body;
            [self.tableView reloadData];
            [self.statuesImg setImage:IMAGENAMED(@"ic_read_question")];
            [self initTimer];
            
        }else{
            
            self.step = answer_step_read_content;
            self.currentReadTime = 0;
            [self playContent];
            
        }
        
    }else if (self.step == answer_step_read_content)
    {

        self.currentReadTime = self.currentReadTime + 1;
        if (views > self.currentReadTime) {
            [self playContent];
            return;
        }
       
        if (self.lastTime > 0) {
            
            self.step = answer_step_wait_read;
            [self.statuesImg setImage:[UIImage imageNamed:@"icon_daolishi"] ];
            [self initTimer];
            return;
            
        }
        
        int index = self.questionIsDoingIndex;
        HSQuestion *tr = self.model.questions[index];
        if (tr.children.count > 0) {
            self.currentReadTime = 0;
            self.step = answer_step_read_sub_question;
            [self playQuestion];
            return;
        }else{
            if (self.recordStartWarn) {
                self.recordStartWarn = NO;
                [self recordContent];
            }else{
                [self playRecordWarnStart];
            }
           
        }
           
    }else if (self.step == answer_step_read_sub_question) {
        
        self.currentReadTime = self.currentReadTime + 1;
        if (views > self.currentReadTime) {
            [self playQuestion];
            return;
        }
        
        
        if (self.lastTime > 0) {
            
            self.step = answer_step_sub_wait_read;
            [self.statuesImg setImage:[UIImage imageNamed:@"icon_daolishi"] ];
            [self initTimer];
            return;
            
        }
        
        if (self.recordStartWarn) {
            self.recordStartWarn = NO;
            [self recordSubQuestionAnswer];
        }else{
            [self playRecordWarnStart];
        }
        
    }else if (self.step == answer_step_wait_read) {
        
        if (self.recordStartWarn) {
            self.recordStartWarn = NO;
            [self recordContent];
        }else{
            [self playRecordWarnStart];
        }
        
    }else if (self.step == answer_step_sub_wait_read) {
        
        if (self.recordStartWarn) {
            self.recordStartWarn = NO;
            [self recordSubQuestionAnswer];
        }else{
            [self playRecordWarnStart];
        }
    }else if (self.step == answer_step_answer_record||self.step == answer_step_answe_sub_questionr_record) {
        
        
        if (self.recordEndWarn) {
            self.recordEndWarn = NO;
            if (self.step == answer_step_answer_record) {
               
               if (self.model.questions.count > self.questionIsDoingIndex + 1 ) {
                   
                   [self nextQuestion];
                   
               }else{
                   [self stopActivity];
               }
               
           }
            
            if (self.step == answer_step_answe_sub_questionr_record) {
                
                int index = self.questionIsDoingIndex;
                HSQuestion *tr = self.model.questions[index];
                if (tr.children.count > self.isDoingSubQuestionIndex + 1 ) {

                    [self nextSubQuestion];
                    
                }else{
                    [self stopActivity];
                }
                
            }
            
        }else{
            [self playRecordWarnStart];
        }
        
    }
        
}
- (void)testProgress
{
    if (self.step == answer_step_title_read) {
        
        if (self.model.templateSettings.listeningAndSpeakingRule.lookTime > 0||self.model.templateSettings.listeningAndSpeakingRule.rootLookTime > 0) {
            self.step = answer_step_look_question;
            if (self.model.templateSettings.listeningAndSpeakingRule.lookTime > 0)
            {
                self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.lookTime;
            }
            if (self.model.templateSettings.listeningAndSpeakingRule.rootLookTime > 0)
            {
                self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.rootLookTime;
            }
            int index = self.questionIsDoingIndex;
            HSQuestion *tr = self.model.questions[index];
            self.showQuestion = tr;
            self.playingText = tr.trunk.body;
            [self.tableView reloadData];
            [self.statuesImg setImage:IMAGENAMED(@"ic_read_question")];
            [self initTimer];
            
        }else{
            
            self.step = answer_step_read_content;
           
            [self playContent];
            
        }
        
    }else if (self.step == answer_step_read_content)
    {

        self.currentReadTime =  self.currentReadTime + 1;
        
        if (self.model.templateSettings.listeningAndSpeakingRule.audioViews > self.currentReadTime) {
            [self playContent];
            return;
        }
        
        int index = self.questionIsDoingIndex;
        HSQuestion *tr = self.model.questions[index];
        if (tr.children.count > 0) {
            self.currentReadTime = 0;
            self.step = answer_step_read_sub_question;
            [self playQuestion];
            return;
        }
           
            
        if (self.model.templateSettings.listeningAndSpeakingRule.readyTime > 0||self.model.templateSettings.listeningAndSpeakingRule.rootReadyTime > 0) {
            
            self.step = answer_step_wait_read;
            [self.statuesImg setImage:[UIImage imageNamed:@"icon_daolishi"] ];
            
            if (self.model.templateSettings.listeningAndSpeakingRule.readyTime > 0)
            {
                self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.readyTime;
            }
            if (self.model.templateSettings.listeningAndSpeakingRule.rootReadyTime > 0)
            {
                self.lastTime = self.model.templateSettings.listeningAndSpeakingRule.rootReadyTime;
            }
            
            [self initTimer];
            
        }else{
            
            if (self.recordStartWarn) {
                self.recordStartWarn = NO;
                [self recordContent];
            }else{
                [self playRecordWarnStart];
            }
            
        }
    }else if (self.step == answer_step_read_sub_question) {
        
        self.currentReadTime =  self.currentReadTime + 1;
        if (self.model.templateSettings.listeningAndSpeakingRule.audioViews > self.currentReadTime) {
            [self playQuestion];
            return;
        }
        
        
        if (self.recordStartWarn) {
            self.recordStartWarn = NO;
            [self recordSubQuestionAnswer];
        }else{
            [self playRecordWarnStart];
        }
        
    }else if (self.step == answer_step_wait_read) {
        
        if (self.recordStartWarn) {
            self.recordStartWarn = NO;
            [self recordContent];
        }else{
            [self playRecordWarnStart];
        }
        
    }else if (self.step == answer_step_answer_record||self.step == answer_step_answe_sub_questionr_record) {
        
        
        if (self.recordEndWarn) {
            self.recordEndWarn = NO;
            if (self.step == answer_step_answer_record) {
               
               if (self.model.questions.count > self.questionIsDoingIndex + 1 ) {
                   
                   [self nextQuestion];
                   
               }else{
                   [self stopActivity];
               }
               
           }
            
            if (self.step == answer_step_answe_sub_questionr_record) {
                
                int index = self.questionIsDoingIndex;
                HSQuestion *tr = self.model.questions[index];
                if (tr.children.count > self.isDoingSubQuestionIndex + 1 ) {

                    [self nextSubQuestion];
                    
                }else{
                    [self stopActivity];
                }
                
            }
            
        }else{
            [self playRecordWarnStart];
        }
        
    }
}
- (void)setLastTime:(NSInteger)lastTime
{
    _lastTime = lastTime;
    [PlayManager sharPlayManager].useTime++;
    NSLog(@"HHHHHHHHHHHH%f",[PlayManager sharPlayManager].useTime);
}
- (void)setStep:(answer_step)step
{
    _step = step;
    NSString *title = @"开始答题";
    if (self.step == answer_step_look_question) {
        title = @"查看问答题";
    }else if (self.step == answer_step_read_content)
    {
        title = @"播放听力";
    }else if (self.step == answer_step_read_sub_question)
    {
        title = @"播放题目";
        
    }else if (self.step == answer_step_wait_read)
    {
        title = @"准备答题";
    }else if (self.step == answer_step_answer_record)
    {
        title = @"录音答题";
    }else if (self.step == answer_step_answe_sub_questionr_record)
    {
        title = @"录音问答";
    }
    
    if (self.step == answer_step_answer_record||self.step == answer_step_answe_sub_questionr_record) {
        [self.nextBtn setTitle:@"完成录音" forState:UIControlStateNormal];
    }else{
        [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    }
    
}
- (UIImage *)getGifImageWithName:(NSString *)name
{
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    return  [UIImage sd_imageWithGIFData:data];
    
}
- (void)dealloc
{
   
    [self stop];
}
@end
